package xyz.kuailemao.mvc.handler;

import com.github.pagehelper.PageInfo;
import entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import xyz.kuailemao.service.api.RoleService;
import xyz.kuailemao.util.ResultEntity;

import java.util.List;

/**
 * 创建时间：2022/8/28 1:15
 */
// @Controller
// @ResponseBody
// 上面两个注解作用的的组合就是 RestController，可以查看源码
@RestController
public class RoleHandler {

    @Autowired
    private RoleService roleService;

    // @ResponseBody
    @RequestMapping("/role/remove/by/role/id/array.json")
    public ResultEntity<String> removeByRoleIdArray(@RequestBody List<Integer> roleIdList){

        roleService.removeRole(roleIdList);

        return ResultEntity.successWithoutData();
    }


    // @ResponseBody
    @RequestMapping("role/update.json")
    public ResultEntity<String> updateRole(Role role){

        roleService.updateRole(role);

        return ResultEntity.successWithoutData();
    }

    // @ResponseBody
    @RequestMapping("role/save.json")
    public ResultEntity<String> saveRole(Role role){

        roleService.saveRole(role);

        return ResultEntity.successWithoutData();
    }

    // 需要部长的角色
    @PreAuthorize("hasRole('部长')")
    // @ResponseBody
    @RequestMapping("/role/get/page/info.json")
    public ResultEntity<PageInfo<Role>> getPageInfo(
            @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize,
            @RequestParam(value = "keyword",defaultValue = "") String keyword
    ){
        // 调用 service 方法获取分页数据
        PageInfo<Role> pageInfo = roleService.getPageInfo(pageNum, pageSize, keyword);

        // 封装到 ResultEntity 对象中返回（如果上面的操作抛出异常，交给异常映射机制处理）
        return ResultEntity.successWithData(pageInfo);
    }
}
